<?php

/**
 * 
 * @author yuxun
 *
 */
class ResourceService extends Service{
	
	public static function indexHeader($params){
		$header = array(
				'id'         => array('text' => 'ID', 'rule' => 'int'),
				's_version'     => array('text' => '服务器版本号'),
				'apk' => array('text' => 'apk 地址'),
				'platform' => array('text' => '平台'),
				'channel' => array('text' => '渠道'),
				'v_num' => array('text' => '版本号'),
				'is_valid' => array('text' => '是否有效'),
				'download_path'=> array('text' => '下载路径'),
				'create_time'=> array('text' => '添加时间'),
				'create_user' => array('text' => PubFunc::t('创建人')),
				'automatic_time'     => array('text' => '定时时间', 'width' => '140px'),
				'info'          => array('text' => '任务情况', 'width' => '300px'),
		);
		if($params['type'] == 3){
			$header['renovate'] = array('text' => '资源刷新情况', 'width' => '100px');
		}
		$header['action'] = array('text' => '操作');
		return $header;
	}
	
	public static function indexData($params){
		$modResource = new ModResource();
		$result = $modResource->page($params);
		
		$condition = array();
		$condition['g'] = $params['g'];
		
		$is_validList = self::is_validList();
		$userList = self::userList();
		foreach($result['data'] as &$v){
			$is_valid = "";
			$valid = $v['is_valid'];
			if($v['is_valid'] == 2) {
				$is_valid = "<span class='changeVisible yes' data-id='".$v['id']."'><i class='fa fa-check-circle'></i>有效</span>";
			}
			if($v['is_valid'] == 1){
				$is_valid = "<span class='changeVisible no' data-id='".$v['id']."'><i class='fa fa-ban'></i>无效</span>";
			}
			
			$v['is_valid'] = $is_valid;
			
			$v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
			$v['create_user'] = $userList[$v['create_user']];
			//$v['is_valid'] = $is_validList[$v['is_valid']];
			//$v['action']   .= ' <a href="'.PubFunc::buildUrl('/oss/?r=resource/delete').'&id='.$v['id'].'" confirm="是否要删除该条信息?">删除</a>';
			if($valid == 1){  //设置定时自动修改为有效的时间
				$v['action'] .= '&nbsp;&nbsp;<a href="javascript:;" name="setting_automatic" data-id="'.$v['id'].'">设置</a>';
			}
			if($params['type'] == 3){
				$v['action']   .= ' <a href="'.PubFunc::buildBackUrl('/oss/?r=resource/edit&type='.$params['type']).'&id='.$v['id'].'">编辑</a>';
			}
			
			$v['automatic_time'] = $v['automatic_time']? date('Y-m-d H:i:s', $v['automatic_time']) : '';
			
			if($v['is_automatic'] == 2){ //已经跑过
				$v['info'] = '<div style="white-space:normal;">'.$v['automatic_info'].'</div>';
			}
			
			if($v['renovate'] == 0){
				$renovate = '';
			}
			if($v['renovate'] == 1){
				$renovate = '资源刷新失败';
			}
			if($v['renovate'] == 2){
				$renovate = '资源刷新成功';
			}
			$v['renovate'] = $renovate;
		}
		unset($v);
		return $result;
	}
	
	public static function doEdit($id, $params){
		if(empty($id)) return array('state' => false, 'msg' => '信息不存在');
		$user = AccAuth::me();
	    $modResource = new ModResource();
		$obj = $modResource->findByPk($id);
		$info = $obj->getAttributes();
		
		
		$game = PubBase::getCurrentGame();
		$resoure_path = $params['resoure_url'];
		$platform = $info['platform'];
		$channel = $info['channel'];
		$platform_dir = $platform."/";
		$channel_dir = $channel."/";
		
		$ip = self::getIp();	
		if($ip == '127.0.0.1'){
			$all_path = 'F:/usr/download/'.$game.'/'.$platform_dir.$channel_dir;
		}else if($ip == '192.168.1.10'){
			//$all_path = '/xujiawen_test/download/'.$game.'/'.$platform_dir.$channel_dir;
			$all_path = '/home/webuser/webapp/download/'.$game.'/'.$platform_dir.$channel_dir;
		}else if($ip == '123.58.17.219'){
			//$all_path = '/xujiawen_test/download/'.$game.'/'.$platform_dir.$channel_dir;
			$all_path = '/data/games/d1/s10cdn_res/download/'.$game.'/'.$platform_dir.$channel_dir;
		}

		$v_num = $info['v_num'];
		$old_all_path = $info['all_path'];
		if(!is_dir($all_path) && !mkdir($all_path, 0777, true)){
			return array('state' => false, 'msg' => '找不到解压路径!');
		}
		
		$zip = new ZipArchive;
		if ($zip->open($resoure_path) === true){
			//获取解压包之后最外层文件名称
			$resource = zip_open($resoure_path);
			$dir_resource = zip_read($resource);
			$file_name = zip_entry_name($dir_resource);
				
			$zip->extractTo($all_path);
			$zip->close();
				
			@unlink($resoure_path);
			self::deldir($old_all_path.'/'); //解压成功之后，将原先的文件夹清空
			@rmdir($old_all_path.'/'); //删除剩下的空文件夹
			
			if(rename($all_path.$file_name, $all_path.$v_num)){	
				$update = array();
				$update['s_version'] = $params['s_version'];
				$update['apk'] = $params['apk'];
				$update['update_user']  = $user['UserID'];
				$update['update_time']  = time();
				$result = $modResource->updateByPk($id, $update);
				if($result){
					//刷新资源
					$exec_l = 'sudo /data/sh/web/wserver_other.sh flush_cdnres '.$info['channel'].' '.$info['v_num'];
					exec($exec_l,$output,$return_var);
					if($return_var == 0){
						$json_array = json_decode($output[0],true);
						if($json_array['code'] == 200){
							//标记刷新资源失败
							$update = array();
							$update['renovate'] = 2;
							$modResource->updateByPk($id, $update);
							return array('state' => true, 'msg' => '操作成功');
						}else{
							//标记刷新资源失败
							$update = array();
							$update['renovate'] = 1;
							$modResource->updateByPk($id, $update);
							return array('state' => false, 'msg' => '资源刷新失败');
						}
					}else{
						//标记刷新资源失败
						$update = array();
						$update['renovate'] = 1;
						$modResource->updateByPk($id, $update);
						return array('state' => false, 'msg' => '刷新资源执行脚本失败');
					}
					
				}else{
					return array('state' => false, 'msg' => '修改记录失败');
				}
		
			}else{
				return array('state' => false, 'msg' => '修改版本目录失败， '.$all_path.$file_name);
			}		
		}else{
			return array('state' => false, 'msg' => '解压失败!');
		}
	}
	
	//清空文件夹函数和清空文件夹后删除空文件夹函数的处理
	public static function deldir($path){
		//如果是目录则继续
		if(is_dir($path)){
			//扫描一个文件夹内的所有文件夹和文件并返回数组
			$p = scandir($path);
			
			foreach($p as $val){
				//排除目录中的.和..
				if($val !="." && $val !=".."){
					//如果是目录则递归子目录，继续操作
					if(is_dir($path.$val)){
						//子目录中操作删除文件夹和文件
						self::deldir($path.$val.'/');
						//目录清空后删除空文件夹
						@rmdir($path.$val.'/');
					}else{
						//如果是文件直接删除
						unlink($path.$val);
					}
				}
			}
		}
	}
	
	public static function doAdd($params){
		$user = AccAuth::me();
		$game = PubBase::getCurrentGame();

		$resoure_path = $params['resoure_url'];		
		$platform = $params['platform'];
		$channel = $params['channel'];
		$platform_dir = $platform."/";
		$channel_dir = $channel."/";
				
		//$all_path = '../public/upload/resource/'.$game.'/'.$platform_dir.$channel_dir;
		
		
		$ip = self::getIp();
			
		if($ip == '127.0.0.1'){
			$all_path = 'F:/usr/download/'.$game.'/'.$platform_dir.$channel_dir;
		}else if($ip == '192.168.1.10'){
			//$all_path = '/xujiawen_test/download/'.$game.'/'.$platform_dir.$channel_dir;
			$all_path = '/home/webuser/webapp/download/'.$game.'/'.$platform_dir.$channel_dir;
		}else if($ip == '123.58.17.219'){
			//$all_path = '/xujiawen_test/download/'.$game.'/'.$platform_dir.$channel_dir;
			$all_path = '/data/games/d1/s10cdn_res/download/'.$game.'/'.$platform_dir.$channel_dir;
		}
		
		$all_folder = self::getDir($all_path);
		$v_num = max($all_folder) + 1;
		
		if(!is_dir($all_path) && !mkdir($all_path, 0777, true)){
			return array('state' => false, 'msg' => '找不到解压路径!');			
		}
		
		$zip = new ZipArchive;
		if ($zip->open($resoure_path) === true){
			//获取解压包之后最外层文件名称
			$resource = zip_open($resoure_path);
			$dir_resource = zip_read($resource);
			$file_name = zip_entry_name($dir_resource);
			
			$zip->extractTo($all_path);
			$zip->close();
			
			@unlink($resoure_path);
			
			if(rename($all_path.$file_name, $all_path.$v_num)){
				//记录入库
				$http_post = '';
				if($ip == '127.0.0.1'){
					$http_post = 'http://192.168.1.10';
				}else if($ip == '192.168.1.10'){
					$http_post = 'http://192.168.1.10';
				}else if($ip == '123.58.17.219'){
					$http_post = 'http://res.yiyun.s10.q-dazzle.com';
				}
				
				//$download_path = $_SERVER['HTTP_HOST'].'/public/upload/resource/'.$game.'/'.$platform_dir.$channel_dir.$v_num;
				$download_path = $http_post.'/download/'.$game.'/'.$platform_dir.$channel_dir.$v_num;
				
				$modResource = new ModResource();
				$modResource->game = $game;
				$modResource->resoure_path   = $params['resoure_url']; //上传文件的路径
				$modResource->s_version  = $params['s_version'];	
				$modResource->apk  = $params['apk'];
				$modResource->platform  = $params['platform'];
				$modResource->channel  = $params['channel'];
				$modResource->v_num  = $v_num;  //版本号
				$modResource->all_path  = $all_path.$v_num;  //解压后的路径
				$modResource->download_path  = $download_path;  //下载路径
				$modResource->create_user   = $user['UserID'];
				$modResource->create_time   = time();
				$modResource->update_user   = $user['UserID'];
				$modResource->update_time   = time();
				$modResource->type   = $params['type'];
				$result = $modResource->save();
				if($result){
					return array('state' => true, 'msg' => '操作成功');
				}else{
					return array('state' => false, 'msg' => '添加记录失败');
				}
				
				
			}else{
				return array('state' => false, 'msg' => '修改版本目录失败， '.$all_path.$file_name);
			}
			
			
		}else{
			return array('state' => false, 'msg' => '解压失败!');
		}
			
	}
	
	
	public  static function getDir($dir) {
		$dirArray[]=NULL;
		if (false != ($handle = opendir ( $dir ))) {
			$i=0;
			while ( false !== ($file = readdir ( $handle )) ) {
				//去掉"“.”、“..”以及带“.xxx”后缀的文件
				if ($file != "." && $file != ".."&&!strpos($file,".")) {
					$dirArray[$i]=$file;
					$i++;
				}
			}
			//关闭句柄
			closedir ( $handle );
		}
		return $dirArray;
	}
	
	public static function platformList(){
		return array(
				'win' => 'win',
				'android' => 'android',
				'ios' => 'ios',
		);
	}
	
	public static function channelList($type){
// 		return array(
// 				'110' => '110',
// 				'101' => '101',
// 				'102' => '102',
// 				'100' => '100',
// 				'0' => '0',
// 		);

		$modRecourseChannel = new ModRecourseChannel();
		$game = PubBase::getCurrentGame();
		$params['g'] = $game;
		$params['type'] = $type;
		$list = $modRecourseChannel->select($params);
		$data = array();
		foreach ($list as $key=>$val){
			$channel = '';
			if($val['desc'] != ''){
				$channel = $val['channel']." (".$val['desc'].")";
			}else{
				$channel = $val['channel'];
			}
			$data[$val['channel']] = $channel;
		}
		return $data;
	}
	
	public static function is_validList(){
		return array(
				'1' => '无效',
				'2' => '有效',
		);
	}
	
	public static function upload($files){
		ini_set('file_uploads','ON');
		ini_set('max_input_time','90');
		ini_set('max_execution_time', '180');
		ini_set('post_max_size', '1024M');
		ini_set('upload_max_filesize','1024M');
		ini_set('memory_limit','128M');
		ini_set ( "display_errors", "on" );
		$game = PubBase::getCurrentGame();
		$file = new PubFile();
		$fileName = $files["file"]["name"];
		$fileSize = $files["file"]["size"];
		if($fileSize/1024/1024  > 1024){
			return array('status' => 0, 'msg' =>'文件大于 1 G...!','data'=>'');
		}
		
		$suffixArr = array('zip'); //允许上传的文件后缀
		$check= $file::checkSuffix($fileName,$suffixArr);
		if($check){
			$ip = self::getIp();
			$ext = $file::getSuffix($fileName);
			//$uploadDir = '../public/upload/'.mango.'/';
			
			if($ip == '127.0.0.1'){
				$uploadDir = 'F:/usr/download/';
			}else if($ip == '192.168.1.10'){
				//$uploadDir = '/xujiawen_test/download/';
				$uploadDir = '/home/webuser/webapp/download/';
			}else if($ip == '123.58.17.219'){
				//$uploadDir = '/xujiawen_test/download/';
				$uploadDir = '/data/games/d1/s10cdn_res/download/';
			}	

			//echo $uploadDir;
			
			$uploadName = md5(microtime(true)).'.'.$ext;
			$upload = $file::uploadFile($files["file"],$uploadDir,$uploadName,false,'1073741824');
			if($upload !== true){
				return array('status' => 0, 'msg' =>$upload,'data'=>'');
			}else{
				//$path = dirname(dirname(dirname(dirname(__File__)))).'/public/upload/'.mango.'/'.$uploadName;  //获取绝对路径
				$path = $uploadDir.$uploadName;
				return array('status' => 1, 'msg' =>'上传成功','data'=>$path);
			}
		}else{
			return array('status' => 0, 'msg' =>'上传文件后缀不允许!','data'=>'');
		}
	}
	
	
	public static function change_field($id,$field,$value){
		$attr = array(
				$field      => $value,
		);
		try{
			$modResource = new ModResource();
			$modResource->updateByPk($id, $attr);
			return true;
		}catch (Exception $e){
			return false;
		}
	
	}
	
	public static function get($id){
		$modResource = new ModResource();
		$obj = $modResource->findByPk($id);
	
		if($obj){
			$info = $obj->getAttributes();
			return $info;
		}else{
			return false;
		}
	}
	
	public static function getIp(){
		if(isset($_SERVER)){
			if($_SERVER['SERVER_ADDR']){
				$server_ip=$_SERVER['SERVER_ADDR'];
			}else{
				$server_ip=$_SERVER['LOCAL_ADDR'];
			}
		}else{
			$server_ip = getenv('SERVER_ADDR');
		}
		return $server_ip;
	}
	
	
	/**
	 * 记录文件
	 * @param unknown $id
	 * @return multitype:number string
	 */
	public static function record($id){
		$info = self::get($id);
		if($info !== false){
			$ip = self::getIp();
			if($ip == '127.0.0.1'){
				$tmp_path = "F:/usr/download/";
			}else if($ip == '192.168.1.10'){
				//$tmp_path = '/xujiawen_test/download/';
				$tmp_path = '/home/webuser/webapp/download/';
			}else if($ip == '123.58.17.219'){
				//$tmp_path = '/xujiawen_test/download/';
				$tmp_path = '/data/games/d1/s10cdn_res/download/';
			}
			
			$fp = fopen($tmp_path."upload_log.txt", "a");
			$str = $info['v_num']." ".$info['s_version']." ".$info['platform']." ".$info['channel']." ".$info['download_path']." ".$info['apk']." ".time()."\r\n";
			$fnum = fwrite($fp, $str);
			fclose($fp);
			if($fnum !== false){
				$out = array('status'=>1,'msg'=>'操作成功','data'=>'');
			}else{
				$out = array('status'=>0,'msg'=>'记录文件失败','data'=>'');
			}
		
		}else{
			$out = array('status'=>0,'msg'=>'非法参数','data'=>'');
		}
		
		return $out;
		
	}
	
	/**
	 * 修改定时时间
	 * @param unknown $ids
	 * @param unknown $automatic_time
	 */
	public static function settingAutomatic($ids,$automatic_time){
		if($ids == ''){
			$out = array('status'=>0,'msg'=>'请选择数据','data'=>'');
			return $out;
		}
		 
		if($automatic_time == ''){
			$out = array('status'=>0,'msg'=>'请设置定时更新状态时间','data'=>'');
			return $out;
		}
		
		if(strtotime($automatic_time) < time()){
			$out = array('status'=>0,'msg'=>'请设置大于当前的时间','data'=>'');
			return $out;
		}

		$modResource = new ModResource();
		$ids_array = explode(',', $ids);
		$ids_array = array_unique($ids_array);
		$data = array();
		foreach ($ids_array as $key=>$val){
			$d = array();
			$d['is_automatic'] = 1;
			$d['automatic_time'] = strtotime($automatic_time);
			$modResource->updateByPk($val, $d);
		}

		$out = array('status'=>1,'msg'=>'操作成功','data'=>'');
		return $out;
	}
	

	

}